package org.bjf.modules.wechat.gateway;

import com.alibaba.fastjson2.JSON;
import org.apache.commons.lang3.StringUtils;
import org.bjf.modules.wechat.config.WechatConfig;
import org.bjf.utils.ExceptionAssert;
import org.bjf.utils.HttpObj;
import org.bjf.utils.OkHttp;
import org.bjf.utils.TokenUtil;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.util.UUID;

/**
 * 微信接口
 * 一些官方文档：https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#1
 */
@Component
public class WxGateway {


    /**
     * @param scopeEnum   应用授权作用域
     * @param redirectUrL 回调的地址
     */
    public String getOpenAuthCodeUrl(String appId, WxScopeEnum scopeEnum, String redirectUrL) {
        String url = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=" + WechatConfig.mpAppId +
                "&redirect_uri=" + URLEncoder.encode(redirectUrL) +
                "&response_type=code" +
                "&scope=" + scopeEnum.getScope() +
                "&state=" + TokenUtil.genJwtToken(UUID.randomUUID().toString(), 60 * 15);

        return url;
    }


    /**
     * 通过授权码取 token信息
     *
     * @param code 授权码
     */
    public WxTokenInfoDO getTokenInfoByAuthCode(String code, String appId, String appSecret) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + WechatConfig.mpAppId +
                "&secret=" + WechatConfig.mpAppSecret +
                "&code=" + code +
                "&grant_type=authorization_code";

        HttpObj tokenObj = OkHttp.get(url);
        WxTokenInfoDO tokenInfoDO = JSON.parseObject(tokenObj.getBody(), WxTokenInfoDO.class);

        ExceptionAssert.isTrue(StringUtils.isBlank(tokenInfoDO.getErrcode()), tokenInfoDO.getErrmsg());

        return tokenInfoDO;
    }


    /**
     * 通过token 拉取用户信息
     */
    public WxUserInfoDO getUserInfo(String accessToken, String openid) {
        String url = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=" + accessToken +
                "&openid=" + openid +
                "&lang=zh_CN";


        HttpObj userObj = OkHttp.get(url);
        WxUserInfoDO wxUserInfo = JSON.parseObject(userObj.getBody(), WxUserInfoDO.class);

        ExceptionAssert.isTrue(StringUtils.isBlank(wxUserInfo.getErrcode()), wxUserInfo.getErrmsg());

        return wxUserInfo;
    }


}
